/**
 * 
 */
package trungsi.gea.photos.controller;

import java.util.Date;
import java.util.List;

import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.integration.spring.SpringBean;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import trungsi.gea.photos.domain.Folder;
import trungsi.gea.photos.domain.Photo;
import trungsi.gea.photos.service.FolderService;
import trungsi.gea.photos.util.JsonUtils;
import trungsi.gea.photos.util.StreamUtils;

/**
 * @author trungsi
 *
 */
@UrlBinding("/folder")
public class FolderListActionBean extends BaseActionBean {

	private static Log log = LogFactory.getLog(FolderListActionBean.class);
	
	@SpringBean
	private FolderService folderService;
	
	private Folder folder;
	
	private int limit = 10;
	private Date before;
	
	public void setLimit(int limit) {
		this.limit = limit;
	}
	
	public void setBefore(Date before) {
		this.before = before;
	}
	
	public void setFolder(Folder folder) {
		this.folder = folder;
	}
	
	public Folder getFolder() {
		return folder;
	}
	
	@HandlesEvent("show")
	public Resolution show() {
		return new ForwardResolution("/folder2.jsp");
	}
	
	@HandlesEvent("list")
	public Resolution list() {
		List<Folder> folders = findAll();
		try {
			JSONObject json = new JSONObject();
			json.put("success", true);
			json.put("folders", new JSONArray());
			for (Folder folder : folders) {
				json.append("folders", JsonUtils.toJson(folder));
			}
			json.put("total", countFolder());
			if (!folders.isEmpty()) {
				json.put("before", "" + folders.get(folders.size()-1).getCreatedDate().getTime());
			}
			return new StreamingResolution("text/html", json.toString());
		} catch (JSONException e) {
			log.error(e);
			return new StreamingResolution("text/html", "{success : false, error : '" + e + "'}");
		}
	}

	private int countFolder() {
		return folderService.countAll();
	}

	private List<Folder> findAll() {
		if (before != null)
			return folderService.findAll(before, limit);
		else
			return folderService.findAll(limit);
	}
	
	@HandlesEvent("cover")
	public Resolution cover() {
		Photo photo = folderService.getFirstPhoto(folder);
		if (photo != null) {
			return new StreamingResolution("", StreamUtils.toInputStream(photo.getThumbnail()));
		}
		return null;
		//return new StreamingResolution("text/html", "{success : true, cover : '" + (photo != null ? "/photo?showThumbnail=&photo=" + photo.getId() : "/image/nophoto.gif") + "'}");
	}
}
